package com.gitee.wsl.mathematics.coordinate.polar.ext

import androidx.compose.ui.geometry.Offset
import com.gitee.wsl.mathematics.coordinate.polar.Polar
import com.gitee.wsl.unit.angle.AngleUnit
import com.gitee.wsl.unit.angle.ext.cosF
import com.gitee.wsl.unit.angle.ext.sinF
import kotlin.jvm.JvmName
import kotlin.math.acos

/**
 * Cartesian to polar coordinate transformation.
 */
fun cartesianToPolar(offset: Offset): Polar {
    val distance = offset.getDistance()
    return if (distance == 0f) {
        Polar(0f, AngleUnit.Radians(0.0))
    } else {
        // acos returns an angle between 0 and PI
        var theta = acos(offset.x / distance)
        if (offset.y < 0) {
            theta = -theta
        }
        Polar(offset.getDistance(), AngleUnit.Radians(theta))
    }
}

@JvmName("cartesianToPolar1")
fun Offset.cartesianToPolar(): Polar = cartesianToPolar(this)

fun polarToCartesian(radius: Float, angle: AngleUnit): Offset = angle.polarToCartesian(radius)

fun AngleUnit.polarToCartesian(radius: Float): Offset {
    return Offset(radius * cosF(), radius * sinF())
}